package com.lins.store.aop.checkParam;

import cn.hutool.core.util.StrUtil;
import com.lins.store.entity.ex.MyselfException;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

@Slf4j
@Aspect //标记为切面类
@Component("aspect")
public class CheckAspect {

    @Autowired
    HttpSession session;

    /**
     * 使用around环绕通知的方法
     * @param pjp ProceedingJoinPoint接口表示连接点，指向目标方法的对象
     * @return
     * @throws Throwable
     * execution(方法返回值 包.类.方法(参数))
     */
//    @Around("execution(* com.lins.store.controller.*.*(..))")  //包括注册也会被拦截
//    @Around("execution(* com.lins.store.controller.FileController.*(..))")
    @Around("@annotation(paramNotNullCheck)")
    public Object around(ProceedingJoinPoint pjp,ParamNotNullCheck paramNotNullCheck) throws Throwable {
        MethodSignature signature = ((MethodSignature) pjp.getSignature());
        //得到拦截的方法
        Method method = signature.getMethod();
        //获取方法参数名
        String[] paramNames = signature.getParameterNames();
        //获取参数值
        Object[] paramValues = pjp.getArgs();
        //获取方法参数类型
        Class<?>[] parameterTypes = method.getParameterTypes();

        for (int i = 0; i < paramValues.length; i++) {
            if (StrUtil.equals(parameterTypes[i].getName(), "java.lang.String") ) {
                if (ObjectUtil.isNull(paramValues[i]) || StrUtil.isBlank(StrUtil.toString(paramValues[i]))){
                    return new MyselfException("参数"+paramNames[i]+"不能为空");

                }
            }
            if (ObjectUtil.isNull(paramValues[i])) {
                return new MyselfException("参数"+paramNames[i]+"不能为空");
            }
        }
        return pjp.proceed();
    }


    //切面类中定义增强，pointcut连接点使用@annotation(xxx)来进行定义，传入注解参数
//    @Around(value = "@annotation(my)") //around(my) 与 下面参数名around对应
//    public void processAuthority(ProceedingJoinPoint point, MyAnnotation my) throws Throwable{
//        System.out.println("ANNOTATION welcome");
//        System.out.println("ANNOTATION 调用方法："+ my.methodName());
//        System.out.println("ANNOTATION 调用类：" + point.getSignature().getDeclaringTypeName());
//        System.out.println("ANNOTATION 调用类名" + point.getSignature().getDeclaringType().getSimpleName());
//        Object result = point.proceed();//接入点调用目标方法
//        System.out.println("ANNOTATION login success");
//    }





}
